﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HHF.Models;

namespace HHF.Controllers
{
    public class ContentController : Controller
    {
        private ICmsItemRepository repository;
        
        public ContentController(ICmsItemRepository repository)
        {
            this.repository = repository;
        }

        public ActionResult Index(string slug)
        {
            this.ViewData.Model = slug;
            return View();
        }

        public ActionResult Details(string slug)
        {
            var item = this.repository.All.FirstOrDefault(x => x.Slug == slug);
            if (item == null)
            {
                if (!this.User.IsInRole("Admin"))
                {
                    return this.HttpNotFound();
                }

                item = new CmsItem { Slug = slug, Text = "(Enter text here)" };
                this.repository.InsertOrUpdate(item);
                this.repository.Save();
            }
            return PartialView(item);
        }

        public ActionResult Edit(int id)
        {
            var item = this.repository.Find(id);
            return this.PartialView(item);
        }

        [HttpPost]
        public ActionResult Edit(CmsItem item)
        {
            this.repository.InsertOrUpdate(item);
            this.repository.Save();

            return PartialView("Details", item);
        }

    }
}
